package com.youth.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @ClassName SpringUtil
 * @Description: TODO applicationContext对象是spring3.x框架的上下文对象实例，在项目运行时自动装载Handler内
 * 的所有信息到内存。 applicationContextAware接口方式获取applicationContext对象实例
 * @Componet注解不能去掉，否则不能调用到重写的setApplicationContext方法。
 * @Author yjwu
 * @Date 2019/12/7 14:59
 **/
@Component
public class MySpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (MySpringUtil.applicationContext == null) {
            MySpringUtil.applicationContext = applicationContext;
            System.out.println("set 完毕" + applicationContext);
        }

    }

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取bean
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    //通过class获取bean
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    //通过name和clazz获取指定的bean
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

}
